package com.edooteach.tencent.accessor.impl;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.wechat.entity.cfg.Config;
import com.demo2do.core.wechat.entity.token.Token;
import com.demo2do.core.wechat.rao.corp.CorpTokenRao;
import com.demo2do.core.wechat.utils.WechatUtils;
import com.edooteach.tencent.accessor.CorpTokenAssessor;
import com.edooteach.tencent.accessor.WeappTokenAccessor;

/**
 * 
 * @author mohanlan
 *
 */
@Component("corpTokenAssessor")
public class CorpTokenAssessorImpl implements CorpTokenAssessor {
  
  private static final Logger logger = LoggerFactory.getLogger(WeappTokenAccessor.class);
  
  @Rao
  private CorpTokenRao corpTokenRao;
  
  private Config config;
  
  /**
   * 
   * @param appid
   * @param appsecret
   */
  @Autowired
  public void config(@Value("#{corp['appid']}") String appid, @Value("#{corp['appsecret']}") String appsecret) {
      this.config = new Config(appid, appsecret);
  }

  /*
   * (non-Javadoc)
   * @see com.edooteach.tencent.accessor.WeappTokenAccessor#requestAccessToken()
   */
  public Token requestAccessToken() {
      
      logger.trace("#requestAccessToken - Request global access_token for appid[{}] and appsecret[{}]", this.config.getAppid(), this.config.getAppsecret());
      
      // 1. call rao to get access token
      HttpResult httpResult = corpTokenRao.getAccessToken(config.getAppid(), config.getAppsecret());
      
      if(WechatUtils.isValid(httpResult)) {  // this is a valid response
          
          // 2. get response data
          Map<String, Object> response = httpResult.describe();
          
          String accessToken = (String) response.get("access_token");
          Integer expireTime = (Integer) response.get("expires_in");
          
          return new Token(accessToken, expireTime);
      
      }
      
      throw WechatUtils.toBusinessException(httpResult);
  }

}
